package com.acme.bankapp.network;

import com.acme.bankapp.domain.bank.Bank;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class BankServer {
    ServerSocket providerSocket;
    Socket connection = null;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;
    Bank bank;
    BankReport report;
    boolean closed = false;


    public BankServer() {
    }

    public void startServer(Bank bank) {
        this.bank = bank;
        this.report = new BankReport(this.bank);
        while (!closed) {
            run();
        }
    }

    void run() {
        try {
            providerSocket = new ServerSocket(2004, 10);
            connection = providerSocket.accept();
            System.out.println("Connection received from "
                    + connection.getInetAddress().getHostName());
            out = new ObjectOutputStream(connection.getOutputStream());
            out.flush();
            in = new ObjectInputStream(connection.getInputStream());
            do {
                try {
                    message = (String) in.readObject();
                    System.out.println("client>" + message);
                    if (message == null) {
                        break;
                    } else if (message.trim().equals("bye")) {
                        sendMessage("bye");
                    } else if (message.trim().equals("close")) {
                        sendMessage("closed");
                        closed = true;
                        break;
                    } else {
                        sendMessage(handleMessage(message));
                    }
                } catch (ClassNotFoundException classnot) {
                    System.err.println("Data received in unknown format");
                }
            } while (!message.trim().equals("bye"));
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            try {
                in.close();
                out.close();
                providerSocket.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    String handleMessage(String msg) {
        if (msg.startsWith("add")) {
            return report.add(msg.replace("add", "").trim());
        } else if (msg.startsWith("print")) {
            return report.print();
        } else {
            return "unknown type of message";
        }
    }

    void sendMessage(final String msg) {
        try {
            out.writeObject(msg);
            out.flush();
            System.out.println("server>" + msg);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

}
